<?php

namespace App\Models\Panx;

use App\Services\Utils\Bosable;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;

/**
 * @property int id
 * @property int brand_id
 * @property int sort
 * @property int customer_id
 * @property string name
 * @property string image
 *
 * @property-read Brand brand
 * @property-read Collection|Product[] products
 *
 * @mixin Builder
 */
class BrandSeries extends Model
{

    use Bosable;

    const ID_OTHER = 0;

    protected $guarded = [];
    protected $table = 'brand_series';

    protected $key_bos_key_prefix = 'brand_series/';

    /**
     * @used-by $brand
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function brand()
    {
        return $this->belongsTo(Brand::class, 'brand_id', 'id');
    }

    /**
     * @used-by $products
     *
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function products()
    {
        return $this->hasMany(Product::class, 'brand_series_id', 'id');
    }

    /**
     * @param $image
     * @throws \Exception
     */
    public function setImageAttribute($image)
    {
        if (is_file($image)) {
            $this->attributes['image'] = $this->uploadPostFile($image, $this->key_bos_key_prefix);
        }else{
            $this->attributes['image'] = $image;
        }
    }

    /**
     * @return mixed|null
     */
    public function getImageAttribute()
    {
        if (!$this->attributes['image']) return null;

        return $this->getStaticUrl($this->attributes['image']);
    }

    /**
     * @return BrandSeries
     */
    public static function newOther(): self
    {
        return new self([
            'id'    => self::ID_OTHER,
            'name'  => trans('app.brand_series_other'),
            'image' => null,
            'sort'  => 10000,
        ]);
    }
}
